<template>
  <div style="padding:10px">
    <div v-if="isManager">
      管理员
    </div>
    <div v-else>
      <div style="text-align: center;color:#303133;font-weight: bold;">【{{ store.__toString }}】</div>
      <div>
        <el-tabs v-model="activeName">
          <el-tab-pane label="待发货订单" name="first">
            <div>
              <el-table
                :data="orders"
                style="width: 100%"
              >
                <el-table-column
                  prop="createdTime"
                  label="日期"
                  width="100"
                >
                  <template slot-scope="scope">
                    {{ new Date(scope.row.createdTime) | dateFormat('YYYY-MM-DD') }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="items"
                  label="产品"
                  width="620"
                >
                  <template slot-scope="scope">
                    <!-- <div v-for="(item,index) in scope.row.items" :key="index">
                  <p>{{ item.__toString }}</p>
                </div> -->
                    <div>
                      <el-table
                        :data="scope.row.items"
                        border
                        style="width: 100%"
                      >
                        <el-table-column
                          prop="specification"
                          label="产品"
                          width="300"
                        />
                        <el-table-column
                          prop="quantity"
                          label="购买数"
                          width="80"
                        />
                        <el-table-column
                          prop="shippingedQuantity"
                          label="已发"
                          width="80"
                        />
                        <el-table-column
                          prop="neeToShippingQuantity"
                          label="待发"
                          width="80"
                        />
                        <el-table-column
                          prop="stock"
                          label="库存数"
                          width="80"
                        />
                      </el-table>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="address"
                  label="地址"
                  width="300"
                >
                  <template slot-scope="scope">
                    <div v-if="scope.row.address">
                      <div>{{ scope.row.address }}</div>
                      <div v-if="scope.row.phone">{{ scope.row.name }}({{ scope.row.phone }})</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="staff"
                  label="业务"
                >
                  <template slot-scope="scope">
                    <div>
                      {{ scope.row.staff.__toString }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="comment"
                  label="订单备注"
                  width="180"
                />
                <el-table-column
                  prop="staff"
                  label="操作"
                >
                  <template slot-scope="scope">
                    <el-button slot="reference" type="text" @click="toShipping(scope.row.id)">发货</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
          <el-tab-pane label="待处理采购单" name="second">
            <div>
              <el-table
                :data="purchases"
                style="width: 100%"
              >
                <el-table-column
                  label="日期"
                  width="180"
                >
                  <template slot-scope="scope">
                    {{ new Date(scope.row.createdTime) | dateFormat('YYYY-MM-DD') }}
                  </template>
                </el-table-column>
                <el-table-column
                  label="状态"
                  width="180"
                >
                  <template slot-scope="scope">
                    {{ purchaseStatus[scope.row.status] }}
                  </template>
                </el-table-column>
                <el-table-column
                  label="产品"
                  width="600"
                >
                  <template slot-scope="scope">
                    <el-table
                      :data="scope.row.items"
                      border
                      style="width: 100%"
                    >
                      <el-table-column
                        prop="specification"
                        label="采购产品"
                        width="340"
                      >
                        <template slot-scope="item">
                          {{ item.row.__metadata.specification.__toString }}
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="quantity"
                        label="购买数"
                        width="80"
                      >
                        <template slot-scope="item">
                          {{ item.row.__metadata.quantity }}
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="shippingedQuantity"
                        label="已签收"
                        width="80"
                      >
                        <template slot-scope="item">
                          {{ item.row.__metadata.retrieved }}
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="neeToShippingQuantity"
                        label="待签收"
                        width="80"
                      >
                        <template slot-scope="item">
                          {{ item.row.__metadata.quantity - item.row.__metadata.retrieved }}
                        </template>
                      </el-table-column>
                    </el-table>
                  </template>
                </el-table-column>
                <el-table-column
                  label="发货仓库"
                >
                  <template slot-scope="scope">
                    <div v-if="scope.row.toStore">
                      {{ scope.row.toStore.__toString }}
                    </div>
                    <div v-else>
                      线下供应商
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="comment"
                  label="采购备注"
                />
                <el-table-column
                  label="操作"
                >
                  <template slot-scope="scope">
                    <div v-if="scope.row.status == 'pending'">
                      <!-- <el-popconfirm
                        title="是否确定审核通过？"
                        @confirm="acceptPurchase(scope.row)"
                      > -->
                      <el-button type="text" @click="acceptPurchase(scope.row)">审核通过</el-button>
                      <!-- </el-popconfirm> -->
                      <!-- <el-popconfirm
                        title="是否确定取消申购？"
                        @confirm="cancelPurchase(scope.row)"
                      > -->
                      <el-button type="text" @click="cancelPurchase(scope.row)">取消申购</el-button>
                      <!-- </el-popconfirm> -->
                    </div>
                    <div v-if="scope.row.status == 'accepted'">
                      <div v-if="scope.row.relatedOrder && scope.row.relatedOrder.__metadata.status == 1">
                        <el-button type="text" @click="pay(scope.row)">支付</el-button>
                      </div>
                      <div v-else>
                        <el-button type="text" @click="toRetrive(scope.row.id)">签收</el-button>
                      </div>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
        <!-- <div><el-divider>待发货订单</el-divider></div> -->

      </div>
      <el-dialog
        title="订单发货"
        :visible.sync="showShipping"
        width="60%"
        @cancel="showShipping = false"
        @close="showShipping = false"
      >
        <el-table
          :data="items"
          style="width: 100%"
        >
          <el-table-column
            prop="specificationTitle"
            label="产品"
          />
          <el-table-column
            prop="quantity"
            label="采购数量"
          />
          <el-table-column
            prop="shippingedQuantity"
            label="已发数量"
          />
          <el-table-column
            prop="shippingedQuantity"
            label="发货"
          >
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.shippingQuantity" :min="0" :max="(scope.row.quantity - scope.row.shippingedQuantity)" />
            </template>
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showShipping = false">取 消</el-button>
          <el-button type="primary" @click="shipping">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        title="采购订单签收"
        :visible.sync="showRetrieved"
        width="60%"
        @cancel="showRetrieved = false"
        @close="showRetrieved = false"
      >
        <el-table
          :data="purchaseItems"
          style="width: 100%"
        >
          <el-table-column
            label="产品"
          >
            <template slot-scope="scope">
              {{ scope.row.specification.__toString }}
            </template>
          </el-table-column>
          <el-table-column
            prop="quantity"
            label="采购数量"
          />
          <el-table-column
            prop="retrieved"
            label="已签收数量"
          />
          <el-table-column
            prop="retriveQuantity"
            label="签收数量"
          >
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.retriveQuantity" :min="0" :max="(scope.row.quantity - scope.row.retrived)" />
            </template>
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showRetrieved = false">取 消</el-button>
          <el-button type="primary" @click="retriev">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      store: '',
      isManager: false,
      orders: [],
      showShipping: false,
      items: [],
      activeName: 'first',
      purchases: [],
      showRetrieved: false,
      purchaseStatus: {
        cancelled: '已取消',
        rejected: '已驳回',
        pending: '待审核',
        accepted: '待签收',
        shipping: '已发货',
        retrieved: '已签收'
      },
      purchaseItems: []
    }
  },
  created() {
    this.axios.get(`/api/user`).then((res) => {
      console.log('user', res.data)
      if (res.data.roles.indexOf('ROLE_SUPER_ADMIN') !== -1) {
        console.log('管理员登录')
        this.isManager = true
      } else {
        if (res.data.stores && res.data.stores.length > 0) {
          this.store = res.data.stores[0]
          this.getOrders()
          this.getPurchases()
        } else {
          this.$message.error('您没有门店权限！')
        }
      }
    })
  },
  mounted() {
  },
  beforeDestroy() {
  },
  methods: {
    // store methods--begin
    getOrders() {
      this.axios.get(`/store/${this.store.id}/orders`, {
        params: {
          '@filter': `entity.getStatus() == 2`,
          '@expands': `['entity.items.shippings']`,
          '@order': `entity.createdTime|ASC`
        }
      }).then((res) => {
        console.log('待发货订单', res.data)
        for (const o of res.data) {
          const items = []
          for (const i of o.items) {
            const item = {
              specId: i.__metadata.specification.id,
              specification: i.__metadata.specificationTitle,
              quantity: i.__metadata.quantity,
              shippingedQuantity: 0,
              neeToShippingQuantity: parseInt(i.__metadata.quantity),
              stock: 0
            }
            // 如果有发货记录的，计算发货的数量
            if (i.__metadata.shippings) {
              for (const s of i.__metadata.shippings) {
                item.shippingedQuantity += parseInt(s.__metadata.quantity)
                item.neeToShippingQuantity -= parseInt(s.__metadata.quantity)
              }
            }
            items.push(item)
          }
          o.items = items
        }
        console.log('order', res.data)
        this.orders = res.data
        // 循环查库存
        const promise = []
        for (const o of this.orders) {
          for (const i of o.items) {
            promise.push(
              this.axios.get(`/store/${this.store.id}/stocks`, { params: {
                '@filter': `entity.getSpecification().getId() == ${i.specId}`
              }}).then((res) => {
                if (res.data.length > 0) {
                  i.stock = res.data[0].remains
                }
              })
            )
          }
        }
      })
    },
    // 去发货
    toShipping(id) {
      this.axios.get(`/store/${this.store.id}/order-items`, { params: {
        '@filter': `entity.getOrder().getId() == ${id}`,
        '@expands': `['entity.shippings']`
      }}).then((res) => {
        console.log('items', res.data)
        for (const i of res.data) {
          i['shippingQuantity'] = i.quantity
          // 查是否有发货记录，有的话，还需要进行扣减
          let shippingedQuantity = 0
          if (i.shippings && i.shippings.length > 0) {
            for (const s of i.shippings) {
              shippingedQuantity += s.__metadata.quantity
            }
          }
          i['shippingQuantity'] = parseInt(i.quantity) - shippingedQuantity
          i['shippingedQuantity'] = shippingedQuantity
        }
        // 额外做个判断，如果已经全部发货，并且状态还是2的，就直接变状态
        let finishShipping = true
        for (const i of res.data) {
          if (parseInt(i.quantity) !== parseInt(i.shippingedQuantity)) {
            finishShipping = false
          }
        }
        if (finishShipping) {
          console.log('订单已经全部完成发货')
          this.axios.get(`/store/${this.store.id}/orders/${id}`).then((res) => {
            if (parseInt(res.data.status) === 2) {
              this.$message.success('该订单已经完成发货,无需操作！')
              this.axios.put(`/store/${this.store.id}/orders/${id}`, { status: 3 }).then((res) => {
                this.getOrders()
              })
            }
          })
          return
        }
        this.items = res.data
        this.showShipping = true
      })
    },
    // 发货
    shipping() {
      const shippingData = []
      for (const i of this.items) {
        if (i.shippingQuantity > 0) {
          shippingData.push({
            orderItem: i.id,
            quantity: i.shippingQuantity
          })
        }
      }
      if (shippingData.length > 0) {
        this.axios.post(`/api/order-shippings`, shippingData).then((res) => {
          this.$message.success('发货成功！')
          this.showShipping = false
          this.getOrders()
        })
      } else {
        this.$message.error('没有发货内容！')
      }
    },
    getPurchases() {
      this.axios.get(`/store/${this.store.id}/purchases`, { params: {
        '@filter': `entity.getStatus() == 'pending' || entity.getStatus() == 'accepted'`,
        '@expands': `['entity.relatedOrder']`
      }}).then((res) => {
        console.log('purchase', res.data)
        this.purchases = res.data
      })
    },
    // 审批采购单
    acceptPurchase(purchase) {
      console.log(purchase)
      // 如果有toStore，又未生成订单的，先生成订单，如果已经生成订单的，就不需要生成
      if (purchase.toStore && purchase.relatedOrder == null) {
        this.axios.post(`/store/${this.store.id}/purchases/${purchase.id}/create-order`).then((res) => {
          this.axios.put(`/store/${this.store.id}/purchases/${purchase.id}`, { status: 'accepted' }).then((res) => {
            this.$message.success('审核成功')
            this.getPurchases()
          })
        })
      } else {
        this.axios.put(`/store/${this.store.id}/purchases/${purchase.id}`, { status: 'accepted' }).then((res) => {
          this.$message.success('审核成功')
          this.getPurchases()
        })
      }
    },
    // 取消采购单
    cancelPurchase(purchase) {
      this.axios.put(`/store/${this.store.id}/purchases/${purchase.id}`, { status: 'cancelled' }).then((res) => {
        this.$message.success('采购订单已取消')
        this.getPurchases()
      })
    },
    // 获取签收情况
    toRetrive(id) {
      this.axios.get(`/store/${this.store.id}/purchase-items`, { params: {
        '@filter': `entity.getPurchase().getId() == ${id}`
      }}).then((res) => {
        console.log(res.data)
        for (const i of res.data) {
          i['retriveQuantity'] = i.quantity - i.retrieved
        }
        this.purchaseItems = res.data
        this.showRetrieved = true
      })
    },
    pay(purchase) {
      if (purchase.relatedOrder && parseInt(purchase.relatedOrder.__metadata.status) === 1) {
        console.log(this.store)
        this.axios.post(`api/invoices/${purchase.relatedOrder.__metadata.invoice.id}/pay/balance`).then((res) => {
          this.$message.success('支付成功！')
          this.getPurchases()
        })
      } else {
        this.$message.error('订单不需要支付')
      }
    },
    // 签收
    retriev() {
      let count = this.purchaseItems.length
      for (const i of this.purchaseItems) {
        this.axios.post(`/api/purchase-items/${i.id}/retrieve/${i.retriveQuantity}`).then((res) => {
          count--
          if (count <= 0) {
            this.showRetrieved = false
            this.$message.success('签收完成')
            this.getPurchases()
          }
        })
      }
    }
    // store methods--end
  }
}
</script>

<style lang="scss" scoped>

</style>
